<template>
	<view class="content">
		<view class="title">
			<text class="title-text" style="color: #ff523f;">谐程代驾</text>
			<text class="title-text">欢迎您的加入！</text>
		</view>
		
		<u--form :model="formData" :rules="rules" ref="form">
			<view class="form-item">
				<view class="form-label required">您的姓名</view>
				<u-input v-model="formData.name" placeholder="请输入姓名" />
			</view>

			<view class="form-item">
				<view class="form-label required">您的性别</view>
				<u-radio-group v-model="formData.gender">
					<u-radio label="男" name="0"></u-radio>
					<u-radio label="女" name="1"></u-radio>
				</u-radio-group>
			</view>

			<view class="form-item">
				<view class="form-label required">请输入您的手机号码</view>
				<u-input v-model="formData.phone" placeholder="请输入手机号" />
			</view>

			<view class="form-item">
				<view class="form-label required">您的年龄是否在25-50岁之间</view>
				<u-radio-group v-model="formData.ageRange">
					<u-radio label="是" name="1"></u-radio>
					<u-radio label="否" name="2"></u-radio>
				</u-radio-group>
			</view>

			<view class="form-item">
				<view class="form-label required">输入您想签约的城市</view>
				<view class="picker-input" @click="openCityPicker">
					<text v-if="formData.city">{{formData.city}}</text>
					<text v-else class="placeholder">请选择城市</text>
				</view>
				<u-picker :show="showCityPicker" :columns="cityColumns" mode="multiSelector" @confirm="confirmCity"
					@cancel="showCityPicker = false" @change="changeCity"></u-picker>
			</view>

			<view class="form-item">
				<view class="form-label required">您的准驾车型</view>
				<view class="picker-input" @click="openPicker">
					<text v-if="formData.driverLicense">{{getSelectedLicenseText}}</text>
					<text v-else class="placeholder">请选择车型</text>
				</view>
				<u-picker :show="show" :columns="[driverLicenseTypes]" @confirm="confirmDriverLicense"
					@cancel="show = false" keyName="dictLabel"></u-picker>
			</view>

			<view class="form-item">
				<view class="form-label required">您的驾龄</view>
				<u-radio-group v-model="formData.drivingYears">
					<u-radio label="3年以下" name="1"></u-radio>
					<u-radio label="3-5年" name="2"></u-radio>
					<u-radio label="5年以上" name="3"></u-radio>
				</u-radio-group>
			</view>

			<view class="form-item">
				<view class="form-label required">驾驶证在最近三个月内有无扣满12分记录</view>
				<u-radio-group v-model="formData.points">
					<u-radio label="有扣满12分记录" name="1"></u-radio>
					<u-radio label="无扣满12分记录" name="2"></u-radio>
				</u-radio-group>
			</view>

			<view class="form-item">
				<view class="form-label required">请上传身份证照片</view>
				<view class="upload-box">
					<view class="upload-item">
						<u-upload auto-upload="false" :fileList="formData.idCardFront" @afterRead="afterIdCardFrontRead"
							@delete="deleteIdCardFront" name="身份证正面" maxCount="1">
							<view class="upload-slot">
								<u-icon name="camera-fill" size="30"></u-icon>
								<text>身份证正面</text>
							</view>
						</u-upload>
					</view>
					<view class="upload-item">
						<u-upload :fileList="formData.idCardBack" @afterRead="afterIdCardBackRead"
							@delete="deleteIdCardBack" name="身份证反面" maxCount="1">
							<view class="upload-slot">
								<u-icon name="camera-fill" size="30"></u-icon>
								<text>身份证反面</text>
							</view>
						</u-upload>
					</view>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label required">请上传驾驶证照片</view>
				<view class="upload-box">
					<view class="upload-item">
						<u-upload :fileList="formData.driverLicenseFront" @afterRead="afterDriverLicenseFrontRead"
							@delete="deleteDriverLicenseFront" name="驾驶证正页" maxCount="1">
							<view class="upload-slot">
								<u-icon name="camera-fill" size="30"></u-icon>
								<text>驾驶证正页</text>
							</view>
						</u-upload>
					</view>
					<view class="upload-item">
						<u-upload :fileList="formData.driverLicenseBack" @afterRead="afterDriverLicenseBackRead"
							@delete="deleteDriverLicenseBack" name="驾驶证副页" maxCount="1">
							<view class="upload-slot">
								<u-icon name="camera-fill" size="30"></u-icon>
								<text>驾驶证副页</text>
							</view>
						</u-upload>
					</view>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label required">政治背景是否清白</view>
				<u-radio-group v-model="formData.politicalStatus">
					<u-radio label="是" name="1"></u-radio>
					<u-radio label="否" name="2"></u-radio>
				</u-radio-group>
			</view>

			<view class="form-item">
				<view class="form-label required">是否全职或者兼职</view>
				<u-radio-group v-model="formData.jobType">
					<u-radio label="全职" name="1"></u-radio>
					<u-radio label="兼职" name="2"></u-radio>
				</u-radio-group>
			</view>
		</u--form>

		<view class="submit-btn">
			<u-button type="primary" text="提交" @click="submit"></u-button>
		</view>
	</view>
</template>

<script>
	import {
		getCityList,
		getDriverLicense,
		driberRegister
	} from '@/api/api.js'
	export default {
		data() {
			return {
				formData: {
					name: '',
					gender: '',
					phone: '',
					ageRange: '',
					city: '',
					province: '',
					cityCode: '',
					driverLicense: '',
					driverLicenseValue:'',
					drivingYears: '',
					points: '',
					idCardFront: [],
					idCardFrontValue: '',
					idCardBack: [],
					idCardBackValue: '',
					driverLicenseFront: [],
					driverLicenseFrontValue: '',
					driverLicenseBack: [],
					driverLicenseBackValue: '',
					politicalStatus: '',
					jobType: ''
				},
				show: false,
				showCityPicker: false,
				cityColumns: [],
				cityList: [],
				driverLicenseTypes: [],
				rules: {
					name: {
						type: 'string',
						required: true,
						message: '请输入姓名',
						trigger: ['blur', 'change'],
						min: 2,
						max: 10,
						pattern: /^[\u4e00-\u9fa5]{2,10}$/
					},
					gender: {
						type: 'string',
						required: true,
						message: '请选择性别',
						trigger: ['change']
					},
					phone: {
						type: 'string',
						required: true,
						message: '请输入正确的手机号码',
						trigger: ['blur', 'change'],
						pattern: /^1[3-9]\d{9}$/
					},
					ageRange: {
						type: 'string',
						required: true,
						message: '请选择年龄范围',
						trigger: ['change']
					},
					city: {
						type: 'string',
						required: true,
						message: '请选择签约城市',
						trigger: ['change']
					},
					driverLicense: {
						type: 'string',
						required: true,
						message: '请选择准驾车型',
						trigger: ['change']
					},
					drivingYears: {
						type: 'string',
						required: true,
						message: '请选择驾龄',
						trigger: ['change']
					},
					points: {
						type: 'string',
						required: true,
						message: '请选择是否有扣分记录',
						trigger: ['change']
					},
					politicalStatus: {
						type: 'string',
						required: true,
						message: '请选择政治背景状况',
						trigger: ['change']
					},
					jobType: {
						type: 'string',
						required: true,
						message: '请选择工作类型',
						trigger: ['change']
					}
				}
			}
		},
		computed: {
			getSelectedLicenseText() {
				const selected = this.driverLicenseTypes.find(item => item.dictLabel === this.formData.driverLicense
					.dictLabel);
				console.log(selected)
				return selected ? selected.dictLabel : '';
			}
		},
		methods: {
			openPicker() {
				this.show = true;
			},
			confirmDriverLicense(e) {
				// console.log(e)
				this.formData.driverLicense = e.value[0];
				this.formData.driverLicenseValue = e.value[0].dictValue
				// console.log(this.formData.driverLicense)
				this.show = false;
			},

			// 身份证照片上传相关方法
			afterIdCardFrontRead(event) {
				const {
					file
				} = event
				this.$uploadFile('/common/uploadDJ', {
					filePath: file.url,
					name: 'file',
				}).then(res => {
					console.log(res)
					if (res.code == 200) {
						this.formData.idCardFront.push(event.file);
						this.formData.idCardFrontValue = res.data.fileName;
					}
				}).catch(err => {
					console.log(err)
				})

			},
			deleteIdCardFront(event) {
				this.formData.idCardFront.splice(event.index, 1)
				this.formData.idCardFrontValue=''
			},
			afterIdCardBackRead(event) {
				const {
					file
				} = event
				this.$uploadFile('/common/uploadDJ', {
					filePath: file.url,
					name: 'file',
				}).then(res => {
					console.log(res)
					if (res.code == 200) {
						this.formData.idCardBack.push(event.file);
						this.formData.idCardBackValue = res.data.fileName;
					}
				}).catch(err => {
					console.log(err)
				})
			},
			deleteIdCardBack(event) {
				this.formData.idCardBack.splice(event.index, 1)
				this.formData.idCardBackValue=''
			},

			// 驾驶证照片上传相关方法
			afterDriverLicenseFrontRead(event) {
				const {
					file
				} = event
				this.$uploadFile('/common/uploadDJ', {
					filePath: file.url,
					name: 'file',
				}).then(res => {
					console.log(res)
					if (res.code == 200) {
						this.formData.driverLicenseFront.push(event.file);
						this.formData.driverLicenseFrontValue = res.data.fileName;
					}
				}).catch(err => {
					console.log(err)
				})

			},
			deleteDriverLicenseFront(event) {
				this.formData.driverLicenseFront.splice(event.index, 1)
				this.formData.driverLicenseFrontValue=''
			},
			afterDriverLicenseBackRead(event) {
				const {
					file
				} = event
				
				this.$uploadFile('/common/uploadDJ', {
					filePath: file.url,
					name: 'file',
				}).then(res => {
					console.log(res)
					if (res.code == 200) {
						this.formData.driverLicenseBack.push(event.file);
						this.formData.driverLicenseBackValue = res.data.fileName;
					}
				}).catch(err => {
					console.log(err)
				})

			},
			deleteDriverLicenseBack(event) {
				this.formData.driverLicenseBack.splice(event.index, 1)
				this.formData.driverLicenseBackValue=''
			},

			// 表单提交
			submit() {
				// 先验证必填字段
				this.$refs.form.validate().then(valid => {
					if (valid) {
						// 验证姓名是否为汉字
						const namePattern = /^[\u4e00-\u9fa5]{2,10}$/;
						if (!namePattern.test(this.formData.name)) {
							return uni.showToast({
								title: '姓名必须为2-10个汉字',
								icon: 'none'
							});
						}

						// 验证手机号格式
						const phonePattern = /^1[3-9]\d{9}$/;
						if (!phonePattern.test(this.formData.phone)) {
							return uni.showToast({
								title: '请输入正确的手机号码',
								icon: 'none'
							});
						}

						// 验证图片上传
						if (!this.formData.idCardFrontValue) {
							return uni.showToast({
								title: '请上传身份证正面照片',
								icon: 'none'
							});
						}
						if (!this.formData.idCardBackValue) {
							return uni.showToast({
								title: '请上传身份证反面照片',
								icon: 'none'
							});
						}
						if (!this.formData.driverLicenseFrontValue) {
							return uni.showToast({
								title: '请上传驾驶证正页照片',
								icon: 'none'
							});
						}
						if (!this.formData.driverLicenseBackValue) {
							return uni.showToast({
								title: '请上传驾驶证副页照片',
								icon: 'none'
							});
						}

						// 验证年龄范围
						if (!this.formData.ageRange) {
							return uni.showToast({
								title: '请选择年龄范围',
								icon: 'none'
							});
						}

						// 验证城市选择
						if (!this.formData.city) {
							return uni.showToast({
								title: '请选择签约城市',
								icon: 'none'
							});
						}

						// 验证准驾车型
						if (!this.formData.driverLicense) {
							return uni.showToast({
								title: '请选择准驾车型',
								icon: 'none'
							});
						}

						// 验证驾龄
						if (!this.formData.drivingYears) {
							return uni.showToast({
								title: '请选择驾龄',
								icon: 'none'
							});
						}

						// 验证扣分记录
						if (!this.formData.points) {
							return uni.showToast({
								title: '请选择是否有扣分记录',
								icon: 'none'
							});
						}

						// 验证政治背景
						if (!this.formData.politicalStatus) {
							return uni.showToast({
								title: '请选择政治背景状况',
								icon: 'none'
							});
						}

						// 验证工作类型
						if (!this.formData.jobType) {
							return uni.showToast({
								title: '请选择工作类型',
								icon: 'none'
							});
						}

						// 所有验证通过，准备提交数据
						const submitData = {
							name: this.formData.name,
							gender: this.formData.gender,
							phone: this.formData.phone,
							ageRange: this.formData.ageRange,
							province: this.formData.province,
							city: this.formData.cityCode,
							cityCode: this.formData.cityCode,
							driverLicense: this.formData.driverLicenseValue,
							drivingYears: this.formData.drivingYears,
							points: this.formData.points,
							politicalIntegrity: this.formData.politicalStatus,
							jobType: this.formData.jobType,
							idCardFront: this.formData.idCardFrontValue,
							idCardBack: this.formData.idCardBackValue,
							driverLicenseFront: this.formData.driverLicenseFrontValue,
							driverLicenseBack: this.formData.driverLicenseBackValue
						};

						// TODO: 调用提交API
						console.log('提交的数据：', submitData);
						
						driberRegister(submitData).then(res=>{
							console.log(res)
							if(res.code==200){
								uni.showModal({
								        title: '注册成功', 
								        content: '您已成功提交注册申请！后续等待管理人员电话联系', 
								        showCancel: true, 
								        cancelText: '取消', 
								        confirmText: '确认', 
								        success: (res) => {
								            if (res.confirm) {
								                // 用户点击了“确认”按钮
								                console.log('用户选择确认');
								            } else if (res.cancel) {
								                // 用户点击了“取消”按钮
								                console.log('用户选择稍后再说');
								            }
								        },
								        fail: (err) => {
								            console.error('显示模态对话框失败：', err);
								        },
								    });
							}
							if(res.code ==500){
								uni.showToast({
									icon:'none',
									title:res.msg,
									duration:2500
								})
							}
						}).catch(err=>{
							console.log(err)
						})
					}
				}).catch(errors => {
					uni.showToast({
						title: '请填写完整信息',
						icon: 'none'
					});
				});
			},
			async initData() {
				try {
					const cityData = await getCityList();
					const driverLicense = await getDriverLicense();

					console.log(cityData)
					console.log(driverLicense)
					if (cityData.code == 200) {
						this.cityList = cityData.data;
						// 初始化城市选择器的列数据
						this.initCityColumns();
					}
					if (driverLicense.code == 200) {
						this.driverLicenseTypes = driverLicense.data
					}

				} catch (err) {
					console.error('Error fetching data:', error);
					uni.showToast({
						icon: 'none',
						title: '初始化数据失败'
					})
				}
			},
			// 初始化城市选择器的列数据
			initCityColumns() {
				console.log(111)
				const provinces = this.cityList.map(item => item.label);
				const defaultCities = this.cityList[0]?.children.map(item => item.label) || [];
				this.cityList1 = this.cityList[0].children;
				console.log(this.cityList1)
				console.log(this.cityList1.map((item) => item.label))
				this.cityColumns = [provinces, defaultCities];
				console.log(this.cityColumns)
			},
			openCityPicker() {
				this.showCityPicker = true;
			},
			// 处理城市选择器的列变化
			changeCity(e) {
				console.log(e)
				const {
					columnIndex,
					value,
					values
				} = e;
				const [provinceIndex, cityIndex] = e.indexs;
				console.log(provinceIndex)
				console.log(this.cityList[provinceIndex]?.children || [])
				// 当省份列变化时更新城市数据
				if(columnIndex === 0){
					const children = this.cityList[provinceIndex]?.children || [];
					this.$set(this.cityColumns,1,children.map(city => city.label))
				}
			},
			// 确认城市选择
			confirmCity(e) {
				const province = e.value[0];
				const city = e.value[1];
				const provinceData = this.cityList.find(item => item.label === province);
				const cityData = provinceData?.children.find(item => item.label === city);

				this.formData.province = province;
				this.formData.city = `${province}/${city}`;
				this.formData.cityCode = cityData?.cityCode || '';
				console.log(this.formData.cityCode)
				this.showCityPicker = false;
			}
		},
		onLoad() {
			// 初始化数据
			this.initData();
		}
	}
</script>

<style>
	.content {
		padding: 20rpx;
	}

	.form-item {
		margin-bottom: 20rpx;
	}

	.form-label {
		font-size: 28rpx;
		color: #303133;
		margin-bottom: 8rpx;
		width: 100%;
		padding: 10rpx 0;
	}

	.form-label.required::before {
		content: '*';
		color: #fa3534;
		margin-right: 4rpx;
	}

	:deep(.u-radio) {
		margin-right: 40rpx;
		margin-bottom: 10rpx;
	}

	:deep(.u-radio-group) {
		flex-wrap: wrap;
	}

	.upload-box {
		display: flex;
		flex-wrap: wrap;
		justify-content: center;
		margin: 0 -10rpx;
		padding-top: 8rpx;
	}

	.upload-item {
		width: 300rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: center;
	}

	.upload-slot {
		width: 200rpx;
		height: 200rpx;
		border: 1px dashed #dcdfe6;
		border-radius: 6rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.upload-slot text {
		font-size: 24rpx;
		color: #909399;
		margin-top: 10rpx;
	}

	.submit-btn {
		margin-top: 40rpx;
		padding: 0 20rpx;
	}

	.picker-input {
		height: 80rpx;
		padding: 0 20rpx;
		border: 1px solid #dcdfe6;
		border-radius: 4rpx;
		display: flex;
		align-items: center;
	}

	.picker-input .placeholder {
		color: #909399;
	}
	
	.title {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 30rpx;
	}
	.title-text {
		font-size: 38rpx;
		margin-bottom: 10rpx;
	}
</style>